#!/bin/bash

if [ ! -f ~/.ssh/id_rsa.pub ]; then
    ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa
fi

pubkey=`cat ~/.ssh/id_rsa.pub`
user=$1
ip=$2
port=$3
password=$4
if [ -z "$ip" ] || [ -z "$password" ];then
	echo "ip or password is null."
	exit
fi

if [ -z "$port" ];then
	port=22
fi
dir="/home/$user"
if [[ "$user" == 'root' ]]; then
    dir="/root"
fi

test ! -f ~/.ssh/known_hosts && touch ~/.ssh/known_hosts

LINE_NUM=$(cat ~/.ssh/known_hosts | grep -n $ip | cut -d : -f 1)

if  test ! -z "$LINE_NUM" ; then
    sed -i "$LINE_NUM d" ~/.ssh/known_hosts
fi

expect -v
test $? != 0 && yum -y install expect

/usr/bin/expect << EOF
set timeout 10
spawn ssh -p$port $user@$ip
expect {
	"*yes/no" { send "yes\r"; exp_continue}
	"*password:" { send "$password\r" }
}
expect "#*"
send "test ! -d $dir/.ssh && mkdir $dir/.ssh;echo $pubkey >> $dir/.ssh/authorized_keys\r"
expect "#*"
send "exit\r"
EOF
